package com.zhika.zishi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zhika.zishi.R;
import com.zhika.zishi.adapter.Answerer2Adapter;
import com.zhika.zishi.adapter.AnswererAdapter;
import com.zhika.zishi.adapter.ViewsPagerAdapter;
import com.zhika.zishi.beans.AnswererBean;
import com.zhika.zishi.customview.TitleView;
import com.zhika.zishi.interfaces.TitleInterface;
import com.zhika.zishi.util.LogUtil;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by shi-02 on 2015/4/21.
 */
public class InviteAnswerActivity extends BaseActivity implements View.OnClickListener {

    private final String TAG = "InviteAnswerActivity";

    private GridView gridView;

    private ArrayList<AnswererBean> selectedAnswererList = new ArrayList<>();

    private Answerer2Adapter answererAdapter;

    private LinearLayout searchLayout;

    private LinearLayout search2Layout;

    private RelativeLayout searchLayout2;

    private TextView cancelText;

    private ViewPager systemViewPager;

    private ViewsPagerAdapter systemAdapter;

    private ViewPager friendsViewPager;

    private ViewsPagerAdapter friendsAdapter;

    private ArrayList<View> viewList = new ArrayList<>();

    private ArrayList<View> friendsViewList = new ArrayList<>();

    private TitleView titleView;

    private  float density;

    private int size;

    private HorizontalScrollView horizontalScrollView;

    private ArrayList<ArrayList<AnswererBean>> answererBeanListList = new ArrayList<>();

    private HashMap<ArrayList<AnswererBean>,AnswererAdapter> answererAdapterHashMap = new HashMap<>();

    private TextView numAnswererText;

    private TextView sureText;

    //屏幕的宽度
    private int screenWidth;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
             switch (msg.what){
                 case 1:

                     LogUtil.e(TAG,"到handler了");
                     Bundle bundle = msg.getData();
                     AnswererBean bean = (AnswererBean) bundle.getSerializable("answerer");
                     selectedAnswererList.add(bean);
                     numAnswererText.setText(String.valueOf(selectedAnswererList.size()));
                     answererAdapter.notifyDataSetInvalidated();
                     addGridViewWidth();
                     break;
                 case 2:
                     LogUtil.e(TAG,"到handler了2");
                     Bundle bundle1 = msg.getData();
                     AnswererBean bean1 = (AnswererBean) bundle1.getSerializable("selected_answerer");
                     selectedAnswererList.remove(bean1);
                     numAnswererText.setText(String.valueOf(selectedAnswererList.size()));
                     for (int i = 0;i<answererBeanListList.size();i++){
                         ArrayList<AnswererBean> answererBeans = answererBeanListList.get(i);
                         for (int k = 0;k<answererBeans.size();k++){
                             AnswererBean bean2 = answererBeans.get(k);
                             if (bean2 == bean1){
                                 LogUtil.e(TAG,"找到一样的answererBean了");
                                 AnswererAdapter adapter = answererAdapterHashMap.get(answererBeans);
                                 adapter.changeStateImageView(bean1);
                             }
                         }
                     }
                     reduceGridViewWidth();
                     break;

             }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.invite_answer_layout);

        initView();

    }

    private void initView() {

        addTestData();
        systemViewPager = (ViewPager) findViewById(R.id.invite_answer_system_view_pager);
        systemAdapter = new ViewsPagerAdapter(viewList);
        systemViewPager.setAdapter(systemAdapter);

        addFriendsTestData();
        friendsViewPager = (ViewPager) findViewById(R.id.invite_answer_friends_view_pager);
        friendsAdapter = new ViewsPagerAdapter(friendsViewList);
        friendsViewPager.setAdapter(friendsAdapter);

//        addSelectedTestData();
        gridView = (GridView) findViewById(R.id.invite_answer_grid_view);
        answererAdapter = new Answerer2Adapter(this, selectedAnswererList,handler);

        gridView.setAdapter(answererAdapter);


        size = selectedAnswererList.size();
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        density = dm.density;
        screenWidth = dm.widthPixels;

        int width = 80;

        int allWidth = (int) (20 * (size - 1)*density  + width * size*density);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                allWidth, LinearLayout.LayoutParams.MATCH_PARENT);
        gridView.setLayoutParams(params);
        gridView.setColumnWidth(width);
        gridView.setHorizontalSpacing(20);
        gridView.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
        gridView.setNumColumns(size);

        LogUtil.e(TAG,"allWidth="+allWidth);



        searchLayout = (LinearLayout) findViewById(R.id.invite_search_layout);
        searchLayout2 = (RelativeLayout) findViewById(R.id.invite_search_layout_2);

        search2Layout = (LinearLayout) findViewById(R.id.invite_search_2_layout);
        search2Layout.setOnClickListener(this);

        cancelText = (TextView) findViewById(R.id.invite_answer_cancel_text);
        cancelText.setOnClickListener(this);

        titleView = (TitleView) findViewById(R.id.invite_title_view);
        titleView.setLeftButtonText("返回");
        titleView.setMiddleRowText("邀请回答");
        titleView.hideRightButton();
        titleView.setTitleViewInterface(new TitleInterface() {
            @Override
            public void leftTitleListener() {
                finish();
            }

            @Override
            public void middleTitleListener() {

            }

            @Override
            public void rightTitleListener() {

            }
        });

        horizontalScrollView = (HorizontalScrollView) findViewById(R.id.invite_answer_horizontal_view);

        numAnswererText = (TextView) findViewById(R.id.invite_answer_num_text);
        sureText = (TextView) findViewById(R.id.invite_answer_sure_text);
        sureText.setOnClickListener(this);

        numAnswererText.setText(String.valueOf(selectedAnswererList.size()));

    }

    private void addTestData() {
        int totalNum = 14;
        int lastItem = totalNum % 3;
        int viewPage = totalNum / 3;
        LogUtil.e(TAG, "页数：" + viewPage + ";剩余的item个数：" + lastItem);
        for (int i = 0; i < viewPage; i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.my_grid_view, null);
            GridView gridView = (GridView) view.findViewById(R.id.m_grid_view);
            ArrayList<AnswererBean> answererList = new ArrayList<>();
            for (int k = 0; k < 3; k++) {
                AnswererBean bean = new AnswererBean();
                bean.setIndex(i*10+k);
                bean.setType("no_select");
                bean.setNicknameStr("机器人" + i + k);
                answererList.add(bean);
            }
            AnswererAdapter answererAdapter = new AnswererAdapter(this, answererList,handler);

            gridView.setAdapter(answererAdapter);

            answererBeanListList.add(answererList);
            answererAdapterHashMap.put(answererList,answererAdapter);

            viewList.add(view);
        }

        if (lastItem != 0) {
            View view = LayoutInflater.from(this).inflate(R.layout.my_grid_view, null);
            GridView gridView = (GridView) view.findViewById(R.id.m_grid_view);
            ArrayList<AnswererBean> answererList = new ArrayList<>();
            for (int k = 0; k < lastItem; k++) {
                AnswererBean bean = new AnswererBean();
                bean.setType("no_select");
                bean.setNicknameStr("机器人" + k);
                answererList.add(bean);
            }
            AnswererAdapter answererAdapter = new AnswererAdapter(this, answererList,handler);

            gridView.setAdapter(answererAdapter);

            answererBeanListList.add(answererList);
            answererAdapterHashMap.put(answererList,answererAdapter);

            viewList.add(view);
        }
    }

    private void addFriendsTestData() {
        int totalNum = 14;
        int lastItem = totalNum % 3;
        int viewPage = totalNum / 3;
        LogUtil.e(TAG, "页数：" + viewPage + ";剩余的item个数：" + lastItem);
        for (int i = 0; i < viewPage; i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.my_grid_view, null);
            GridView gridView = (GridView) view.findViewById(R.id.m_grid_view);
            ArrayList<AnswererBean> answererList = new ArrayList<>();
            for (int k = 0; k < 3; k++) {
                AnswererBean bean = new AnswererBean();
                bean.setType("no_select");
                bean.setNicknameStr("好友" + i + k);
                answererList.add(bean);
            }
            AnswererAdapter answererAdapter = new AnswererAdapter(this, answererList,handler);

            gridView.setAdapter(answererAdapter);

            answererBeanListList.add(answererList);
            answererAdapterHashMap.put(answererList,answererAdapter);

            friendsViewList.add(view);
        }

        if (lastItem != 0) {
            View view = LayoutInflater.from(this).inflate(R.layout.my_grid_view, null);
            GridView gridView = (GridView) view.findViewById(R.id.m_grid_view);
            ArrayList<AnswererBean> answererList = new ArrayList<>();
            for (int k = 0; k < lastItem; k++) {
                AnswererBean bean = new AnswererBean();
                bean.setType("no_select");
                bean.setNicknameStr("机器人" + k);
                answererList.add(bean);
            }
            AnswererAdapter answererAdapter = new AnswererAdapter(this, answererList,handler);

            gridView.setAdapter(answererAdapter);

            answererBeanListList.add(answererList);
            answererAdapterHashMap.put(answererList,answererAdapter);

            friendsViewList.add(view);
        }
    }

    private void addSelectedTestData() {
        for (int i = 0; i < 2; i++) {
            AnswererBean b = new AnswererBean();
            b.setType("selected");
            b.setNicknameStr("已选");

            selectedAnswererList.add(b);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.invite_search_2_layout:
                search2LayoutListener();
                break;
            case R.id.invite_answer_cancel_text:
                cancelTextListener();
                break;
            case R.id.invite_answer_sure_text:
                sureTextListener();
                break;
        }
    }

    /**
     * 第一次进入搜索界面时，搜索的点击事件
     */
    private void search2LayoutListener() {
        searchLayout2.setVisibility(View.GONE);
        searchLayout.setVisibility(View.VISIBLE);
    }

    /**
     * 在第二个搜索界面中取消的点击事件
     */
    private void cancelTextListener() {
        searchLayout.setVisibility(View.GONE);
        searchLayout2.setVisibility(View.VISIBLE);
    }

    /**
     * 重新设置GridView的宽度，加上一个item的宽度,并显示最新一条数据
     */
    private void addGridViewWidth(){
        int gridViewWidth = (int) (gridView.getWidth()+(80+20)*density);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(gridViewWidth, ViewGroup.LayoutParams.MATCH_PARENT);
        gridView.setLayoutParams(params);
        gridView.setNumColumns(size+1);
        size = size+1;
        if (gridViewWidth>=screenWidth){
            horizontalScrollView.smoothScrollBy((gridViewWidth-screenWidth),gridView.getHeight());
        }
//        horizontalScrollView.smoothScrollTo((int) (gridViewWidth+(80+20)*density),gridView.getHeight());

    }

    /**
     * 在已选的用户中，删除一个元素时，减小gridview的宽度和列数
     */
    private void reduceGridViewWidth(){
        int gridViewWidth = (int) (gridView.getWidth() - (80+20)*density);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(gridViewWidth, ViewGroup.LayoutParams.MATCH_PARENT);
        gridView.setLayoutParams(params);
        gridView.setNumColumns(size-1);
        size = size - 1;
    }

    /**
     * 确定按钮的点击事件
     */
    private void sureTextListener(){
        Intent intent = new Intent(InviteAnswerActivity.this,QuizActivity.class);
        intent.putExtra("answerers",selectedAnswererList);
        startActivity(intent);
    }

}
